﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using BoYuanCore.Framework;
using KeXin.Model.Config;
using KeXin.IService;
using KeXin.Service;
using FreeSqlExtensions;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using JwtHelper = KeXin.Service.JwtHelper;

namespace KeXin.Service
{
    public class LoginService:BaseService,ILoginService
    {
        private readonly IFreeSql _fsql;
        private readonly IHttpContextAccessor _accessor;
        private readonly JwtConfig _jwtConfig;


        public LoginService(IFreeSql fsql,IHttpContextAccessor accessor, JwtConfig jwtConfig)
        {
            _fsql = fsql;
            _accessor = accessor;
            _jwtConfig = jwtConfig;
        }

        public async Task<(string,long)> LoginAsync(string username, string pwd )
        {
            var pwdStr = Security.MD5Helper.GetMd5Pwd(pwd);
            var admin = await _fsql.Select<Entity.SysAdmin>()
                .Where(p => p.Isdel == false && p.Password == pwdStr && p.LoginName == username)
                .FirstAsync(p => new {p.ID, p.RealName});

            if (admin == null)
            {
                return ("用户名或密码错误", 0);
            }
            else
            {
                return (admin.RealName, admin.ID);
            }
        }

        /// <summary>
        /// 获取token和刷新token
        /// </summary>
        /// <param name="userRealName"></param>
        /// <param name="adminId"></param>
        /// <returns></returns>
        public (string, string) GetAccessTokenAndRefreshToken(string userRealName, string adminId)
        {
            var claims = new Claim[]
            {
                new Claim(ClaimName.UserRealName,userRealName),
                new Claim(ClaimName.AdminId,adminId),
            };

            var accessToken=  JwtHelper.CreateToken(claims, _jwtConfig);
            var refreshToken =  JwtHelper.GetRefreshToken(claims, _jwtConfig);

            return (accessToken, refreshToken);
        }

        /// <summary>
        /// 获取刷新token
        /// </summary>
        /// <returns></returns>
        public string RefreshToken()
        {
            var token = _accessor.HttpContext.Request.Headers["Authorization"].ToString().Split(' ')[1];

            return  JwtHelper.RefreshAccessToken(token, _jwtConfig);
        }
    }
}
